<template>
    <div class="app-container">
        <div class="head">
            <img src="@/assets/img/Layout/position.png" />
            <p class="see-block">退料单新建</p>
        </div>
        <div class="view-container">
            <el-row class="status-title">
                <el-col class="mr20 width100">
                    <el-button
                        class="btn-success width100"
                        type="primary"
                        @click="submitForm()"
                    >提交</el-button>
                </el-col>
                <el-col :span="10" class="status-container">
                    <div class="status-item">
                        <span class="active">草稿</span>
                        <span>待审核</span>
                        <span>待退料</span>
                        <span>已退料</span>
                    </div>
                </el-col>
            </el-row>
            <el-form ref="form" :model="form" label-width="100px" class="mt30">
                <el-row>
                    <el-col :span="9">
                        <el-form-item label="单据编码:" prop="code">
                            <el-input v-model="form.code" placeholder="系统自动生成" disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :span="9">
                        <el-form-item label="业务日期:" prop="businessDate">
                            <el-input v-model="form.businessDate" placeholder="系统自动生成" disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :span="9">
                        <el-form-item label="业务部门:" prop="businessUnit">
                            <el-select v-model="form.businessUnit" style="width:100%;" placeholder="请选择">
                                <el-option label="生产部" value="生产部"></el-option>
                                <el-option label="财务部" value="财务部"></el-option>
                                <el-option label="质检部" value="质检部"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="9">
                        <el-form-item label="业务类型:" prop="businessType">
                            <el-select v-model="form.businessType" style="width:100%;" placeholder="请选择">
                                <el-option label="生产退料" value="0"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="18">
                        <el-col :span="12">
                            <el-form-item label="原领料单:" prop="materialRequisitionCode">
                                <el-select v-model="form.materialRequisitionCode" style="width:82%;" placeholder="请选择" filterable @change="changeMaterialRequisition">
                                    <el-option
                                        v-for="item in materialRequisitionList"
                                        :key="item.id"
                                        :label="item.code"
                                        :value="item.code">
                                    </el-option>
                                </el-select>
                                <el-button type="primary" size="small" class="btn-success" icon="el-icon-search" style="position:absolute;right:0;top:0;bottom:0;width:15%;font-size:14px;" @click="onMaterialRequisitionList"></el-button>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="是否整单退:">
                                <el-radio v-model="form.ifWholeOrder" label="1" @change="onIfWholeOrder">否</el-radio>
                                <el-radio v-model="form.ifWholeOrder" label="0" @change="onIfWholeOrder">是</el-radio>
                            </el-form-item>
                        </el-col>
                    </el-col>
                    <el-col :span="9">
                        <el-form-item label="接收仓库:" prop="receivingWarehouse">
                            <el-select v-model="form.receivingWarehouse" style="width:100%;" placeholder="请选择领料单" disabled>
                                <el-option
                                    v-for="item in warehouseList"
                                    :key="item.warehouseId"
                                    :label="item.name"
                                    :value="item.warehouseId">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="9">
                        <el-form-item label="退货原因:" prop="reasonsForReturn">
                            <el-input v-model="form.reasonsForReturn" placeholder="" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="9">
                        <el-form-item label="退料人:" prop="returnerName">
                            <el-select v-model="form.returnerName" style="width:100%;" placeholder="请选择">
                                <el-option
                                    v-for="item in returnerNameList"
                                    :key="item.userId"
                                    :label="item.userName"
                                    :value="item.userName">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="9">
                        <el-form-item label="备注:" prop="remark">
                            <el-input v-model="form.remark" placeholder="" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row class="mb20">
                  <el-col :span="24">
                      <el-button class="btn-success width100 mr20" type="primary" @click="scanCode">扫码退料</el-button>
                      <el-button class="btn-delete width100" type="primary" @click="delScanCode">删除扫码</el-button>
                  </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-table :data="productData">
                            <el-table-column label="序号" type="index" align="center" width="50" />
                            <el-table-column :label="item.label" :prop="item.prop" :width="item.width" v-for="(item, index) in columns" :key="index" align="center">
                                <template slot-scope="scope">
                                    <template v-if="item.type == '1'">
                                        <template v-if="scope.row.scanCode == '0'">
                                            <el-input v-model="scope.row[item.prop]" disabled />
                                        </template>
                                        <el-autocomplete
                                            v-else
                                            style="width:100%;"
                                            v-model="scope.row[item.prop]"
                                            :fetch-suggestions="searchCode"
                                            placeholder="请选择"
                                            @select="val => handleSelect(val, scope.row, scope.$index)"
                                        ></el-autocomplete>
                                    </template>
                                    <template v-if="item.type == '2'">
                                        <template v-if="scope.row.scanCode == '0'">
                                            <el-input v-model="scope.row[item.prop]" disabled />
                                        </template>
                                        <el-autocomplete
                                            v-else
                                            style="width:100%;"
                                            v-model="scope.row[item.prop]"
                                            :fetch-suggestions="searchName"
                                            placeholder="请选择"
                                            @select="val => handleSelect(val, scope.row, scope.$index)"
                                        ></el-autocomplete>
                                    </template>
                                    <template v-if="item.type == '3'">
                                        {{ scope.row[item.prop] }}
                                    </template>
                                    <template v-if="item.type == 'planNum'">
                                        <template v-if="scope.row.scanCode == '0'">
                                            <el-input placeholder="扫码退料" v-model="scope.row[item.prop]" disabled />
                                        </template>
                                        <template v-else>
                                            <el-input placeholder="请输入数量" v-model="scope.row[item.prop]" @input="(val) => inputNum(val, scope.row, 'planNum')" @blur="saveData(scope.row)" :disabled="scope.row.positionList ? true : false" />
                                        </template>
                                    </template>
                                    <template v-if="item.type == 'realNum'">
                                        <template v-if="scope.row.scanCode == '0'">
                                            <el-input placeholder="扫码退料" v-model="scope.row[item.prop]" disabled />
                                        </template>
                                        <template v-else>
                                            <el-input placeholder="请输入数量" v-model="scope.row[item.prop]" @input="(val) => inputNum(val, scope.row, 'realNum')" @blur="saveData(scope.row)" :disabled="scope.row.positionList ? true : false" />
                                        </template>
                                    </template>
                                    <template v-if="item.type == 'warehouse'">
                                        <el-select v-model="scope.row[item.prop]" style="width:100%;" placeholder="" disabled>
                                            <el-option
                                                v-for="item in warehouseList"
                                                :key="item.warehouseId"
                                                :label="item.name"
                                                :value="item.warehouseId">
                                            </el-option>
                                        </el-select>
                                    </template>
                                    <template v-if="item.type == 'position'">
                                        <el-input v-model="scope.row[item.prop]" disabled placeholder="点击按钮搜索">
                                            <el-button slot="append" icon="el-icon-search" @click="onClickWarehouseList(scope.row, scope.$index)"></el-button>
                                        </el-input>
                                    </template>
                                    <template v-if="item.type == 'more'">
                                        <el-tooltip effect="dark" content="多仓位" placement="bottom" >
                                            <span class="el-icon-s-grid more" @click.stop="showMorePosition(scope.row)"></span>
                                        </el-tooltip>
                                    </template>
                                    <template v-if="item.type == 'del'">
                                        <span class="del" v-if="scope.row.scanCode !== '0'" @click="deleteRow(scope.row)">删除</span>
                                    </template>
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-col>
                </el-row>
            </el-form>
        </div>
        <!-- 领料单弹窗列表 -->
        <el-dialog :visible.sync="openMaterialRequisition" width="900px" top="100px" append-to-body center :close-on-click-modal='false' :close-on-press-escape='false' :show-close="false">
            <el-table :data="materialRequisitionList" @row-click="materialRequisitionData">
                <el-table-column label="序号" type="index" align="center" width="50" />
                <el-table-column label="单据编号"  align="center" prop="code" width="150" />
                <el-table-column label="业务日期" align="center" prop="businessDate" width="180" />
                <el-table-column label="领料人" align="center" prop="picker" />
                <el-table-column label="审核人" align="center" prop="approveName" />
                <el-table-column label="状态" align="center" prop="status">
                    <template slot-scope="scope">
                        <div v-if="scope.row.status == '0'">待审核</div>
                        <div v-if="scope.row.status == '1'">待领用</div>
                        <div v-if="scope.row.status == '2'">已领用</div>
                    </template>
                </el-table-column>
            </el-table>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" class="btn-success width100" @click="onHideMaterialRequisition">关闭</el-button>
            </div>
        </el-dialog>
        <!-- 多仓位 -->
        <el-dialog :visible.sync="morePosition" width="900px" top="100px" append-to-body center :close-on-click-modal='false' :close-on-press-escape='false' :show-close="false">
            <el-table :data="moreData" @row-click="scanCodeMorePosition">
                <el-table-column label="名称" align="center" prop="productName" width="150" />
                <el-table-column label="可退数量" align="center" prop="purchaseNum" width="80" />
                <el-table-column label="申退数量" align="center" prop="planNum" width="80" />
                <el-table-column label="实退数量" align="center" prop="endNum" width="100">
                    <template slot-scope="scope">
                        <template v-if="scope.row.scanCode == '0'">
                            <el-input placeholder="扫码领料" v-model="scope.row.endNum" disabled />
                        </template>
                        <template v-else>
                            <el-input placeholder="请输入" @click.native.stop="stopScanCode" v-model="scope.row.endNum" @input="(val) => inputEditNum(val, scope.row)" @blur="(val) => onBlurEditNum(val, scope.row)" />
                        </template>
                    </template>
                </el-table-column>
                <el-table-column label="仓库" align="center" prop="warehouse">
                    <template slot-scope="scope">
                        <el-select v-model="scope.row.warehouse" disabled>
                            <el-option
                                v-for="item in warehouseList"
                                :key="item.warehouseId"
                                :label="item.name"
                                :value="item.warehouseId">
                            </el-option>
                        </el-select>
                    </template>
                </el-table-column>
                <el-table-column label="仓位" align="center" prop="positionName">
                    <template slot-scope="scope">
                        <el-input v-model="scope.row.positionName" disabled placeholder="点击按钮搜索" @click.native.stop="stopScanCode">
                            <el-button slot="append" icon="el-icon-search" @click.stop="morePositionWarehouseList(scope.row, scope.$index)"></el-button>
                        </el-input>
                    </template>
                </el-table-column>
                <el-table-column label="" align="center" width="90px" class-name="small-padding fixed-width">
                    <template slot-scope="scope">
                        <span class="el-icon-circle-plus-outline icon-more-position" @click.stop="onAddMorePosition(scope.row)"></span>
                        <span class="el-icon-circle-close icon-more-position" @click.stop="onDeleteMorePosition(scope.row)" v-if="scope.row.scanCode == '1'"></span>
                    </template>
                </el-table-column>
            </el-table>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" class="btn-success width100" @click="onHideMorePosition">关闭</el-button>
            </div>
        </el-dialog>
        <!-- 扫码框 -->
        <!-- class="input-data" -->
        <input v-model="scanCodeData.code"
            class="input-data"
            ref="getFocus"
            type="password"
            @keydown.enter="numberEnterDown()"
            @keyup.enter="numberEnterUp()"
        />
    </div>
</template>

<script>
import { materialReturnAdd, materialReturnEdit, materialReturnAddSingle, materialReturnEditSingle,materialReturnDel, materialReturnDetail, materialRequisitionList, materialRequisitionDetail, materialReturnScanCode, materialReturnDelScanCode, morePositionList, morePositionAdd, morePositionEdit, morePositionAddSingle, morePositionDelSingle, morePositionUpdate, materialReturnSubmit } from "@/api/system/warehouse/materialReturn"
import { queryWarehouse } from "@/api/system/warehouse/warehouse"
export default {
    name: "add",
    data() {
        return {
            form: {
                id: '',
                code: '',
                businessDate: '', // 业务日期
                businessUnit: '生产部', // 业务部门
                businessType: '0', // 业务类型
                materialRequisitionId: '', // 领料单id
                materialRequisitionCode: '', // 领料单编码
                ifWholeOrder: '1', // 是否整单退 0 是 1 否
                receivingWarehouse: '', // 接收仓库
                reasonsForReturn: '', // 退货原因
                returnerName: '', // 退料人
                remark: '', // 备注
                detailList: [], // 产品信息
            },
            materialRequisitionList: [], // 领料单列表
            warehouseList: [], // 仓库列表
            returnerNameList: [], // 领料人列表
            openMaterialRequisition: false, // 领料单弹窗
            // 表头
            columns: [{
                prop: "productCode",
                label: "物料编码",
                width: 220,
                type: '1'
            },{
                prop: "productName",
                label: "物料名称",
                type: '2',
                width: 220,
            },{
                prop: "productSpace",
                label: "物料规格",
                type: '3',
                width: 180,
            },{
                prop: "batchNumber",
                label: "批次号",
                width: 150,
                type: '3'
            },{
                prop: "picksNum",
                label: "可退数量",
                width: 100,
                type: '3'
            },{
                prop: "planNum",
                label: "申退数量",
                width: 120,
                type: 'planNum'
            },{
                prop: "realNum",
                label: "退货数量",
                width: 120,
                type: 'realNum'
            },{
                prop: "unit",
                label: "单位",
                width: 100,
                type: '3'
            },{
                prop: "warehouse",
                label: "仓库",
                width: 130,
                type: 'warehouse'
            },{
                prop: "positionName",
                label: "仓位",
                width: 200,
                type: 'position'
            },{
                prop: "remark",
                label: "备注",
                width: 200,
                type: '3'
            },{
                label: "",
                width: 50,
                type: 'more'
            },{
                label: "",
                type: 'del',
                width: 80
            }],
            // 产品数据
            productData: [],
            // 领料单搜索产品数据
            searchProduct: [],
            // 扫码数据
            scanCodeData: {
                code: ''
            },
            scanCodeType: '',
            // 多仓位
            morePosition: false,
            moreData: [],
            morePositionData: []
        }
    },
    created(){
        // 获取用户信息
        let userInfo = this.$store.state.user.users
        this.form.returnerName = userInfo.userName
        // 退料人列表
        this.returnerNameList.push({
            userId: userInfo.userId,
            userName: userInfo.userName
        })
        // 仓位数据
        if(this.$route.query.data && this.$route.query.data !== '[object Object]'){
            this.form = this.$route.query.data
            let index = this.$route.query.index
            this.productData = this.$route.query.data.detailList
            materialReturnEditSingle(this.productData[index]).then(res => {
                if(res.code == 200){
                    this.getDetailData()
                    this.$router.push({ query: {} })
                }
            })
        }
        // 多仓位数据
        if(this.$route.query.morePosition && this.$route.query.morePosition !== '[object Object]'){
            this.form = this.$route.query.form
            let data = this.$route.query.morePosition
            let index = this.$route.query.index
            morePositionList(data.businessId).then(res => {
                if(res.code == 200){
                    this.morePosition = true
                    this.moreData = res.rows
                    this.moreData[index] = data
                    morePositionUpdate(this.moreData[index]).then(res =>{
                        if(res.code == 200){
                            this.getDetailData() 
                        }else{
                            this.$modal.msgError(res.msg)
                            morePositionList(data.businessId).then(res => {
                                if(res.code == 200){
                                    res.rows.forEach(item => {
                                        if(item.endNum == 0){
                                            item.endNum = ''
                                        }
                                    })
                                    this.moreData = res.rows
                                }
                            })
                        }
                    })
                    this.$router.push({ query: {} })
                }
            })
        }
        this.getWarehouseList()
        this.getMaterialRequisitionList()
    },
    methods: {
        // 获取领料单列表
        getMaterialRequisitionList(){
            materialRequisitionList('1').then(res => {
                if(res.code == 200){
                    this.materialRequisitionList = res.rows
                }
            })
        },
        // 获取详情数据
        getDetailData(){
            materialReturnDetail(this.form.id).then(res => {
                if(res.code == 200){
                    this.form = res.data
                    if(res.data.detailList !== null){
                        res.data.detailList.forEach(item => {
                            if(item.planNum == 0){
                                item.planNum = ''
                            }
                            if(item.realNum == 0){
                                item.realNum = ''
                            }
                        })
                        this.productData = res.data.detailList
                    }else{
                        this.productData = []
                    }
                    if(this.form.ifWholeOrder == '1'){
                        this.addProduct()
                    }
                }
            })
        },
        // 获取仓库列表
        getWarehouseList(){
            queryWarehouse().then(res => {
                if(res.code == 200){
                    this.warehouseList = res.data
                }
            })
        },
        // 弹窗领料单列表
        onMaterialRequisitionList(){
            this.openMaterialRequisition = true
        },
        // 选中领料单列表
        materialRequisitionData(row){
            this.form.receivingWarehouse = row.receivingWarehouse
            this.form.materialRequisitionId = row.id
            this.form.materialRequisitionCode = row.code
            if(this.form.ifWholeOrder == '1'){
                if(this.form.id){
                    materialReturnEdit(this.form).then(res => {
                        if(res.code == 200){
                            this.getDetailData()
                            materialRequisitionDetail(row.id).then(res => {
                                if(res.code == 200){
                                    this.searchProduct = res.data
                                    this.productData = []
                                    this.addProduct()
                                }
                            })
                        }
                    })
                }else{
                    materialReturnAdd(this.form).then(res => {
                        if(res.code == 200){
                            this.form = res.data
                            this.getDetailData(res.data.id)
                            materialRequisitionDetail(row.id).then(res => {
                                if(res.code == 200){
                                    this.searchProduct = res.data
                                    this.productData = []
                                    this.addProduct()
                                }
                            })
                        }
                    })
                }
            }else{
                if(this.form.id){
                    materialReturnEdit(this.form).then(res => {
                        if(res.code == 200){
                            this.getDetailData()
                        }
                    })
                }else{
                    materialReturnAdd(this.form).then(res => {
                        if(res.code == 200){
                            this.form = res.data
                            this.getDetailData(res.data.id)
                        }
                    })
                }
            }
            this.openMaterialRequisition = false
        },
        // 关闭领料单列表
        onHideMaterialRequisition(){
            this.openMaterialRequisition = false
        },
        onIfWholeOrder(val){
            // console.log(val)
            // 0 是 1否
            this.form.materialRequisitionId = ''
            this.form.materialRequisitionCode = ''
            this.form.receivingWarehouse = ''
            this.productData = []
            this.form.detailList = null
        },
        // 选中领料单
        changeMaterialRequisition(val){
            let data = this.materialRequisitionList.find(item => item.code == val)
            this.form.receivingWarehouse = data.receivingWarehouse
            this.form.materialRequisitionId = data.id
            this.form.materialRequisitionCode = data.code
            if(this.form.ifWholeOrder == '1'){
                if(this.form.id){
                    this.form.detailList = []
                    materialReturnEdit(this.form).then(res => {
                        if(res.code == 200){
                            this.getDetailData()
                            materialRequisitionDetail(data.id).then(res => {
                                if(res.code == 200){
                                    this.searchProduct = res.data
                                    this.productData = []
                                    this.addProduct()
                                }
                            })
                        }
                    })
                }else{
                    materialReturnAdd(this.form).then(res => {
                        if(res.code == 200){
                            this.form = res.data
                            this.getDetailData(res.data.id)
                            materialRequisitionDetail(data.id).then(res => {
                                if(res.code == 200){
                                    this.searchProduct = res.data
                                    this.productData = []
                                    this.addProduct()
                                }
                            })
                        }
                    })
                }
            }else{
                if(this.form.id){
                    this.form.detailList = []
                    materialReturnEdit(this.form).then(res => {
                        if(res.code == 200){
                            this.getDetailData()
                        }
                    })
                }else{
                    materialReturnAdd(this.form).then(res => {
                        if(res.code == 200){
                            this.form = res.data
                            this.getDetailData(res.data.id)
                        }
                    })
                }
            }
        },
        // 编码搜索
        searchCode(val, cb) {
            let list = []
            this.searchProduct.map(item => {
                list.push(Object.assign(
                    {},item,{
                        value: item.productCode
                    }
                ))
            })
            var arr = list
            var results = val ? arr.filter(this.createFilter(val)) : arr
            cb(results)
        },
        // 名称搜索
        searchName(val, cb){
            let list = []
            this.searchProduct.map(item => {
                list.push(Object.assign(
                    {},item,{
                        value: item.productName
                    }
                ))
            })
            var arr = list
            var results = val ? arr.filter(this.createFilter(val)) : arr
            cb(results)
        },
        // 匹配
        createFilter(val) {
            return (res) => {
                return (res.value.toLowerCase().indexOf(val.toLowerCase()) === 0)
            }
        },
        // 选中
        handleSelect(item, row, index){
            // console.log(item)
            row.materialReturnId = this.form.id  // 主表id
            row.materialRequisitionDetailId = item.id // 领料单详情id
            row.productBasicId = item.productBasicId, // 产品Id
            row.productBasicCode = item.productBasicCode, // 产品编码
            row.productBasicName = item.productBasicName, // 产品名称
            row.productId = item.productId // 物料id(SKU)
            row.productCode = item.productCode // 物料编码(SKU)
            row.productName = item.productName // 物料名称(SKU)
            row.productSpace = item.productSpace // 物料规格(SKU)
            row.batchNumber = item.batchNumber // 批次号
            row.picksNum = item.allowReturnNum // 可退数量
            row.planNum = '' // 申退数量(计划数量)
            row.realNum = '' // 退货数量
            row.unit = item.unit // 单位
            row.warehouse = item.warehouse // 仓库
            row.areaId = item.areaId // 区域id
            row.areaName = item.areaName // 区域名称
            row.positionId = item.positionId // 仓位id
            row.positionName = item.positionName // 仓位名称
            row.remark = item.remark // 备注
            // 判断编码是否重复
            let arr = this.productData.filter(item => item.productCode !== '')
            if(arr && arr.length > 0){
                let productCode = arr.map(i => i.productCode)
                let productCodeSet = new Set(productCode)
                let data = arr.find(y => y.productId == item.productId)
                if(productCodeSet.size == productCode.length){
                    materialReturnAddSingle(data).then(res => {
                        if(res.code == 200){
                            this.getDetailData()
                        }
                    })
                }else{
                    this.$modal.msgError('产品已存在，请重新选择！')
                    this.productData.splice(index, 1)
                    let newArr = this.productData.filter(item => item.productCode !== '')
                    this.productData = newArr
                    this.addProduct()
                }
            }
        },
        // 跳转仓库列表页面
        onClickWarehouseList(row, index){
            // 当前选中仓库对应仓库列表的数据
            let isWarehouse = this.warehouseList.find(item => item.warehouseId == row.warehouse)
            // 判断是否启用仓位管理
            if(isWarehouse.openPosition == '0'){
                if(row.scanCode == '0'){
                    morePositionList(row.id).then(res => {
                        if(res.rows.length > 0){
                            this.$modal.msgError('已存在多仓位，请去多仓位编辑!')
                        }else{
                                if(row.realNum > 1){
                                this.$modal.msgError('仓位不能编辑!')
                            }else{
                                this.$router.push({path:"/warehouseManagement/warehouse/list", query:{ type: 'materialReturn', data: this.form, index: index }})
                            }
                        }
                    })
                }else{
                    morePositionList(row.id).then(res => {
                        if(res.rows.length > 0){
                            this.$modal.msgError('已存在多仓位，请去多仓位编辑!')
                        }else{
                            this.$router.push({path:"/warehouseManagement/warehouse/list", query:{ type: 'materialReturn', data: this.form, index: index }})
                        }
                    })
                }
            }else{
                this.$modal.msgError('未启用仓位管理！')
            }
        },
        // 扫码退料
        scanCode(){
            if(this.form.materialRequisitionId !== null && this.form.materialRequisitionId !== ''){
                this.$refs.getFocus.focus()
                this.scanCodeType = "0"
                this.scanCodeData = {
                    materialReturnId: this.form.id,
                    materialRequisitionId: this.form.materialRequisitionId,
                }
                this.$modal.msgSuccess("开始扫码！")
            }else{
                this.$modal.msgError('请选择领料单!')
            }
        },
        // 删除扫码
        delScanCode(){
            if(this.form.materialRequisitionId !== null && this.form.materialRequisitionId !== ''){
                this.$refs.getFocus.focus()
                this.scanCodeType = "1"
                this.scanCodeData = {
                    materialReturnId: this.form.id
                }
                this.$modal.msgSuccess("删除扫码！")
            }else{
                this.$modal.msgError('请选择领料单!')
            }
        },
        numberEnterDown(){
            this.keyDownTime = new Date().getTime()
        },
        numberEnterUp(){
            this.keyUpTime = new Date().getTime()
            if (this.keyUpTime - this.keyDownTime < 30) {
                // 扫码枪触发
                let newCode = this.common.codeRule(this.scanCodeData.code)
                // let code = this.scanCodeData.code.split("=")
                // let newCode = code[code.length - 1]
                // console.log(newCode)
                if(newCode.length == 13 || newCode.length == 20){
                    this.scanCodeData.code = newCode
                    if(this.scanCodeType == '0'){
                        // 扫码领料
                        materialReturnScanCode(this.scanCodeData).then(res => {
                            if(res.code == 200){
                                this.getDetailData()
                                this.scanCodeData.code = ''
                                this.$refs.getFocus.focus()
                                this.$modal.msgSuccess("扫码成功")
                            }else{
                                this.scanCodeData.code = ''
                                this.$refs.getFocus.focus()
                                this.$modal.msgError(res.msg)
                            }
                        })
                    }else if(this.scanCodeType == '2'){
                        // 扫码领料
                        materialReturnScanCode(this.scanCodeData).then(res => {
                            if(res.code == 200){
                                this.getDetailData()
                                morePositionList(this.morePositionData.businessId).then(res => {
                                    this.moreData = res.rows
                                })
                                this.scanCodeData.code = ''
                                this.$refs.getFocus.focus()
                                this.$modal.msgSuccess("扫码成功")
                            }else{
                                this.scanCodeData.code = ''
                                this.$refs.getFocus.focus()
                                this.$modal.msgError(res.msg)
                            }
                        })
                    }else{
                        // 删除扫码
                        materialReturnDelScanCode(this.scanCodeData).then(res => {
                            if(res.code == 200){
                                this.getDetailData()
                                this.scanCodeData.code = ''
                                this.$refs.getFocus.focus()
                                this.$modal.msgSuccess("删除成功")
                            }else{
                                this.scanCodeData.code = ''
                                this.$refs.getFocus.focus()
                                this.$modal.msgError(res.msg)
                            }
                        })
                    }
                }else{
                    this.scanCodeData.code = ''
                    this.$refs.getFocus.focus()
                    this.$modal.msgError('扫码错误，请重新扫码!')
                }
            }else{
                // 直接按键盘触发
                let newCode = this.common.codeRule(this.scanCodeData.code)
                // let code = this.scanCodeData.code.split("=")
                // let newCode = code[code.length - 1]
                // console.log(newCode)
                if(newCode.length == 13 || newCode.length == 20){
                    this.scanCodeData.code = newCode
                    if(this.scanCodeType == '0'){
                        // 扫码领料
                        materialReturnScanCode(this.scanCodeData).then(res => {
                            if(res.code == 200){
                                this.getDetailData()
                                this.scanCodeData.code = ''
                                this.$refs.getFocus.focus()
                                this.$modal.msgSuccess("扫码成功")
                            }else{
                                this.scanCodeData.code = ''
                                this.$refs.getFocus.focus()
                                this.$modal.msgError(res.msg)
                            }
                        })
                    }else if(this.scanCodeType == '2'){
                        // 扫码领料
                        materialReturnScanCode(this.scanCodeData).then(res => {
                            if(res.code == 200){
                                this.getDetailData()
                                morePositionList(this.morePositionData.businessId).then(res => {
                                    this.moreData = res.rows
                                })
                                this.scanCodeData.code = ''
                                this.$refs.getFocus.focus()
                                this.$modal.msgSuccess("扫码成功")
                            }else{
                                this.scanCodeData.code = ''
                                this.$refs.getFocus.focus()
                                this.$modal.msgError(res.msg)
                            }
                        })
                    }else{
                        // 删除扫码
                        materialReturnDelScanCode(this.scanCodeData).then(res => {
                            if(res.code == 200){
                                this.getDetailData()
                                this.scanCodeData.code = ''
                                this.$refs.getFocus.focus()
                                this.$modal.msgSuccess("删除成功")
                            }else{
                                this.scanCodeData.code = ''
                                this.$refs.getFocus.focus()
                                this.$modal.msgError(res.msg)
                            }
                        })
                    }
                }else{
                    this.scanCodeData.code = ''
                    this.$refs.getFocus.focus()
                    this.$modal.msgError('扫码错误，请重新扫码!')
                }
            }
        },
        // 阻止事件
        stopScanCode(){},
        // 多仓位扫码
        scanCodeMorePosition(row){
            if(row.scanCode == '0'){
                this.$refs.getFocus.focus()
                this.morePositionData = row
                this.scanCodeType = "2"
                this.scanCodeData = {
                    materialReturnId: this.form.id,
                    materialRequisitionId: this.form.materialRequisitionId,
                    positionId: row.id
                }
                this.$modal.msgSuccess("开始扫码！")
            }
        },
        // 数量验证
        inputNum(val, row, item){
            if(val == '' || val == undefined){
                if(item == 'planNum'){
                    this.$modal.msgError('申退数量不能为空!')
                }else{
                    this.$modal.msgError('退货数量不能为空!')
                }
            }else{
                if(/^[1-9]\d*$|^0$/.test(val) == false){
                    if(item == 'planNum'){
                        this.$modal.msgError('申退数量必须是数字！')
                        row.planNum = ''
                        return false
                    }else{
                        this.$modal.msgError('退货数量必须是数字！')
                        row.realNum = ''
                        return false
                    }
                }else{
                    if(JSON.parse(val) <= 0){
                        if(item == 'planNum'){
                            row.planNum = ''
                            this.$modal.msgError('申退数量必须大于0!')
                        }else{
                            row.realNum = ''
                            this.$modal.msgError('退货数量必须大于0!')
                        }
                    }else{
                        if(item == 'planNum'){
                            if(JSON.parse(val) > row.picksNum){
                                row.planNum = ''
                                this.$modal.msgError('申退数量不能大于可退数量，请重新输入!')
                            }
                        }else{
                            if(JSON.parse(val) > row.planNum){
                                row.realNum = ''
                                this.$modal.msgError('退货数量不能大于申退数量，请重新输入!')
                            }
                        }
                    }
                }
            }
        },
        // 保存数量
        saveData(row){
            if(row.planNum !== null && row.planNum !== ''){
                materialReturnEditSingle({id: row.id, planNum: row.planNum, realNum: row.realNum }).then(res => {
                    if(res.code == 200){
                        this.getDetailData()
                    }
                })
            }
        },
        // 多仓位
        showMorePosition(row){
            // console.log(row)
            // 当前选中仓库对应仓库列表的数据
            let isWarehouse = this.warehouseList.find(item => item.warehouseId == row.warehouse)
            // 判断是否启用仓位管理
            if(isWarehouse.openPosition == '0'){
                if(row.areaId !== '' && row.areaId !== null){
                    if(row.planNum !== '' && row.planNum !== null){
                        morePositionList(row.id).then(res => {
                            if(res.code == 200){
                                this.morePosition = true
                                if(res.rows.length > 0 && row.realNum > 0 && row.planNum > 0){
                                    this.moreData = res.rows
                                }else{
                                    // 多仓位新建
                                    let obj = {
                                        businessId: row.id,
                                        productId: row.productId,
                                        productCode: row.productCode,
                                        productName: row.productName,
                                        purchaseNum: row.picksNum,
                                        planNum: row.planNum,
                                        endNum: row.realNum,
                                        warehouse: row.warehouse,
                                        areaId: row.areaId,
                                        areaName: row.areaName,
                                        positionId: row.positionId,
                                        positionName: row.positionName,
                                        batchNumber: row.batchNumber,
                                        scanCode: row.scanCode
                                    }
                                    morePositionAdd(obj).then(res => {
                                        if(res.code == 200){
                                            morePositionList(row.id).then(res => {
                                                res.rows.forEach(item => {
                                                    if(item.endNum == 0){
                                                        item.endNum = ''
                                                    }
                                                })
                                                this.moreData = res.rows
                                            })
                                        }
                                    })
                                }
                            }
                        })
                    }else{
                        this.$modal.msgError('申退数量不能为空！')
                    }
                }else{
                    this.$modal.msgError('请选择仓位！')
                }
            }else{
                this.$modal.msgError('未启用仓位管理！')
            }
        },
        // 多仓位数量验证
        inputEditNum(val, row, item){
            if(row.areaId !== null ){
                if(val == '' || val == undefined){
                    this.$modal.msgError('实退数量不能为空!')
                }else{
                    if(/^[1-9]\d*$|^0$/.test(val) == false){
                        this.$modal.msgError('实退数量必须是数字！')
                        row.endNum = ''
                        return false
                    }else{
                        if(JSON.parse(val) <= 0){
                            row.endNum = ''
                            this.$modal.msgError('实退数量必须大于0!')
                        }else{
                            if(JSON.parse(val) > row.planNum){
                                row.endNum = ''
                                this.$modal.msgError('实退数量不能大于申退数量，请重新输入!')
                            }
                        }
                    }
                }
            }else{
                row.endNum = ''
                this.$modal.msgError('请选择仓位!')
            }
        },
        // 多仓位数据保存
        onBlurEditNum(val, row){
            if(val.target.value == null || val.target.value == ''){
                this.$modal.msgError('实退数量不能为空!')
            }else{
                let num = 0
                this.moreData.forEach(item => {
                    num += Number(item.endNum)
                    return num
                })
                if(num > row.planNum){
                    row.endNum = ''
                    this.$modal.msgError('实退数量不能大于申退数量!')
                }else{
                    morePositionEdit(row).then(res => {
                        if(res.code == 200){
                            this.getDetailData()
                        }
                    })
                }
            }
        },
        // 多仓位单个新建
        onAddMorePosition(row){
            let num = 0
            this.moreData.forEach(item => {
                num += Number(item.endNum)
                return num
            })
            if(num < row.planNum){
                let obj = {
                    businessId: row.businessId,
                    businessType: 5,
                    productId: row.productId,
                    productCode: row.productCode,
                    productName: row.productName,
                    purchaseNum: row.purchaseNum,
                    planNum: row.planNum,
                    endNum: '',
                    warehouse: row.warehouse,
                    areaId: '',
                    areaName: '',
                    positionId: '',
                    positionName: '',
                    batchNumber: row.batchNumber,
                    scanCode: row.scanCode
                }
                morePositionAddSingle(obj).then(res => {
                    if(res.code == 200){
                        morePositionList(row.businessId).then(res => {
                            res.rows.forEach(item => {
                                if(item.endNum == 0){
                                    item.endNum = ''
                                }
                            })
                            this.moreData = res.rows
                        })
                    }
                })
            }else{
                this.$modal.msgError('不能新建仓位！')
            }
        },
        // 多仓位删除一行
        onDeleteMorePosition(row){
            this.$modal.confirm('是否确认删除当前数据？', '删除').then(() => {
                morePositionDelSingle(row.id).then(res => {
                    if(res.code == 200){
                        morePositionList(row.businessId).then(res => {
                            res.rows.forEach(item => {
                                if(item.planNum == 0){
                                    item.planNum = ''
                                }
                                if(item.endNum == 0){
                                    item.endNum = ''
                                }
                            })
                            this.moreData = res.rows
                        })
                    }
                })
            }).catch(() => {})
        },
        // 多仓位跳转仓库列表页面
        morePositionWarehouseList(row, index){
            if(row.endNum > 0){
                this.$modal.msgError('申退数量已存在，不能编辑!')
            }else{
                this.$router.push({path:"/warehouseManagement/warehouse/list", query:{ type: 'materialReturnMorePosition', form: this.form, list: row, index: index}})
            }
        },
        // 关闭多仓位
        onHideMorePosition(){
            this.morePosition = false
            this.getDetailData()
        },
        // 添加一条产品信息
        addProduct(){
            let data = {
                key: {
                    productId: ''
                }
            }
            this.columns.forEach(item =>{
                data.key[item.prop] = ''
            })
            this.productData.push(JSON.parse(JSON.stringify(data.key)))
        },
        // 删除数据
        deleteRow(item){
            if(item.productId !== ''){
                this.$modal.confirm('是否确认删除当前数据？', '删除').then(() => {
                    materialReturnDel(item.id).then(res => {
                        if(res.code == 200){
                            this.getDetailData()
                        }
                    })
                }).catch(() => {})
            }else{
                this.$modal.msgError('最少保留一条可编辑数据！')
            }
        },
        // 提交
        submitForm(){
            let arr = this.productData.filter(item => item.productCode !== '')
            let planNum = arr.every(val => !!val.planNum)
            let realNum = arr.every(val => !!val.realNum)
            if(arr.length > 0){
                if(planNum == true){
                    if(realNum == true){
                        this.form.detailList = arr
                        let data = this.form
                        data.approveStatus = 0
                        data.status = 1
                        this.$modal.loading("正在提交")
                        materialReturnSubmit(data).then(res => {
                            if(res.code == 200){
                                this.$modal.msgSuccess("新建成功")
                                this.$tab.closeOpenPage({ path: "/material/materialReturn" })
                                this.$modal.closeLoading()
                            }
                        })
                    }else{
                        this.$modal.msgError('退货数量不能为空！')
                    }
                }else{
                    this.$modal.msgError('申退数量不能为空！')
                }
            }else{
                this.$modal.msgError('产品不能为空！')
            }
        }
    }
}
</script>

<style scoped>
.del{
  color: #ff0000;
  cursor: pointer;
}
::v-deep .el-input .el-input-group__append{
  padding: 0 10px;
}
.more{
  font-size: 30px;
  cursor: pointer;
}
::v-deep .el-dialog__header{
  display: none;
}
.icon-more-position{
  font-size: 22px;
  margin: 0 5px;
  cursor: pointer;
}
</style>